package biz.yfsoft.app.fastframework.jfinal.extra;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

import com.jfinal.render.Render;
import com.jfinal.render.RenderException;
import com.jfinal.render.RenderFactory;

public class BytesRender extends Render {

	private static final String DEFAULT_CONTENT_TYPE = "application/octet-stream";
	
	private String name;
	
	private byte[] data;
	
	public BytesRender(String name,byte[] data) {
		this.name = name;
		this.data = data;
	}
	
	private String encodeFileName(String fileName) {
		try {
			return new String(fileName.getBytes("GBK"), "ISO8859-1");
		} catch (UnsupportedEncodingException e) {
			return fileName;
		}
	}
	@Override
	public void render() {
		if (data == null ) {
			RenderFactory.me().getErrorRender(404).setContext(request, response).render();
			return ;
        }
		// ---------
		response.setHeader("Accept-Ranges", "bytes");
		response.setHeader("Content-disposition", "attachment; filename=" + encodeFileName(name));
        response.setContentType(DEFAULT_CONTENT_TYPE);
        
        // ---------
        response.setHeader("Content-Length", String.valueOf(data.length));
        OutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            outputStream.write(data, 0, data.length);
            outputStream.flush();
        }
        catch (IOException e) {
        	if (getDevMode())	throw new RenderException(e);
        }
        catch (Exception e) {
        	throw new RenderException(e);
        }
        finally {
            if (outputStream != null)
            	try {outputStream.close();} catch (IOException e) {}
        }

	}

}
